package com.gitee.cui.server.handler;

import com.gitee.cui.common.cocurrent.FutureTaskScheduler;
import com.gitee.cui.common.common.bean.msg.ProtoMsg;
import com.gitee.cui.server.server.ServerSession;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.timeout.IdleStateEvent;
import io.netty.handler.timeout.IdleStateHandler;
import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.TimeUnit;

/**
 * @author cuiqingqiang
 * @version 1.0
 * @date 2021/10/28 9:48
 **/
@Slf4j
public class HeartBeatServerHandler extends IdleStateHandler {

    private static final int READ_IDLE_GAP = 150;

    public HeartBeatServerHandler() {
        super(READ_IDLE_GAP, 0, 0, TimeUnit.SECONDS);
    }

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        if (!(msg instanceof ProtoMsg.Message)) {
            super.channelRead(ctx, msg);
            return;
        }

        ProtoMsg.Message message = (ProtoMsg.Message) msg;
        ProtoMsg.HeadType type = message.getType();
        if (ProtoMsg.HeadType.HEART_BEAT == type) {
            FutureTaskScheduler.add(() -> {
                if (ctx.channel().isActive()) {
                    ctx.writeAndFlush(msg);
                }
            });
        }

        super.channelRead(ctx, msg);
    }

    @Override
    protected void channelIdle(ChannelHandlerContext ctx, IdleStateEvent evt) throws Exception {
        log.info("{}秒内未读到心跳数据，关闭连接", READ_IDLE_GAP);
        ServerSession.closeSession(ctx);
    }
}
